<template>
  <div class="row">
    <select-package-modal :visible.sync="visible" @addPackage="addPackage"></select-package-modal>
    <div class="col-md-12">
      <Portlet title="所选包件列表">
        <div slot="tools">
          <el-button type="primary" @click.prevent="visible = true">选择包件</el-button>
        </div>
        <el-form :model="model" label-position="left" ref="elForm" label-width="100px">
            <el-table
              :data="model.chMoveLocationItemList"
              style="width:100%"
              border
              height="500"
              class="text-center"
            >
              <el-table-column
                prop="cargoOwnerName"
                label="商家名称"
              >
              </el-table-column>
              <el-table-column
                width="200"
                label="移库包件数量">
                <template slot-scope="scope">
                  <el-form-item label-width="0" :prop="'chMoveLocationItemList.' + scope.$index + '.locationMoveNum'" :rules="[
                        {required: true, type: 'number', message: '移库包件数量必须', trigger: 'blur', max: scope.row.locationAvailableNum, min: 1}
                     ]">
                    <el-input v-model.number="scope.row.locationMoveNum" label="描述文字"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                prop="locationAvailableNum"
                label="在库包件数量">
              </el-table-column>
              <el-table-column
                prop="packageName"
                label="包件名称">
              </el-table-column>
              <el-table-column
                prop="packageCode"
                label="包件编号">
              </el-table-column>
              <el-table-column
                prop="productName"
                label="所属产品">
              </el-table-column>
              <el-table-column
                prop="productNo"
                label="产品编号">
              </el-table-column>
              <el-table-column
                prop="locationAddress"
                label="现有库位">
              </el-table-column>
              <el-table-column
                width="170"
                prop="toLocationId"
                label="目标库位">
                <template slot-scope="scope">
                  <el-form-item label-width="0" :prop="'chMoveLocationItemList.' + scope.$index + '.toLocationId'" :rules="[
                        {required: true, message: '库位必须', trigger: 'change'}
                      ]">
                    <select-position v-model="scope.row.toLocationId" :showSameUp="scope.$index > 0" @change="selectChange(scope.$index)"></select-position>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                min-width="60"
                label="操作"
              >
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="danger"
                    @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
      </Portlet>
      <Portlet>
        <div class="row">
          <div class="col-xs-4 col-xs-offset-4">
            <el-button :loading="loading" class="btn-block" @click.prevent="submit" type="primary">提交</el-button>
          </div>
        </div>
      </Portlet>
    </div>
  </div>
</template>
<script>
import Portlet from '@/components/Portlet'
import SelectPosition from '@/views/oms/business/SelectPosition'
import {copy, dotData, alert} from '@/utils'
import SelectPackageModal from './SelectPackageModal'
export default {
  name: 'transferAdd',
  components: {
    SelectPackageModal,
    Portlet,
    SelectPosition
  },
  filters: {
  },
  data() {
    return {
      visible: false,
      loading: false,
      model: {
        chMoveLocationItemList: []
      },
      rules: {}
    }
  },
  created() {
  },
  computed: {
    showSameUp() {
      return true
    }
  },
  methods: {
    // 添加产品
    addPackage(arr) {
      let tempMap = new Map()
      this.model.chMoveLocationItemList.forEach(v => {
        tempMap.set(v.locationPackageId, v)
      })
      arr.forEach(v => {
        if (!tempMap.has(v.locationPackageId)) {
          this.$set(v, 'locationMoveNum', 1)
          this.$set(v, 'toLocationId', '')
          this.model.chMoveLocationItemList.push(v)
        } else {
          let item = tempMap.get(v.locationPackageId)
          this.$set(item, 'locationMoveNum', item.locationMoveNum ? item.locationMoveNum + 1 : 1)
        }
      })
    },
    searchFunc() {
    },
    // reset 重置搜索框
    reset(searchForm) {
      this.$refs.searchForm.resetFields()
    },
    // 删除
    handleDelete(index, row) {
      if (this.model.chMoveLocationItemList[index].toLocationId === 'sameUp') {
        this.model.chMoveLocationItemList[index].toLocationId = this.model.chMoveLocationItemList[index].toLocationId
      }
      this.model.chMoveLocationItemList.splice(index, 1)
    },
    // change
    selectChange(index) {
      for (let i = index + 1; i < this.model.chMoveLocationItemList.length; i++) {
        if (!this.model.chMoveLocationItemList[i].toLocationId) {
          this.$set(this.model.chMoveLocationItemList[i], 'toLocationId', 'sameUp')
        }
      }
    },
    submit() {
      this.$refs.elForm.validate(result => {
        if (!result) {
          alert('验证未通过')
          return
        }
        let tempArr = []
        let data = copy(this.model, true)
        if (Array.isArray(data.chMoveLocationItemList)) {
          if (data.chMoveLocationItemList.length <= 0) {
            alert('请选择移库包件')
            return
          }
          for (let i = 0; i < data.chMoveLocationItemList.length; i++) {
            if (data.chMoveLocationItemList[i].toLocationId === data.chMoveLocationItemList[i].locationId) {
              alert('同一库位不能进行移库操作')
              return
            }
            if (data.chMoveLocationItemList[i].toLocationId === 'sameUp') {
              data.chMoveLocationItemList[i].toLocationId = data.chMoveLocationItemList[i - 1].toLocationId
            }
            tempArr.push({
              packageId: data.chMoveLocationItemList[i].packageId,
              cargoOwnerId: data.chMoveLocationItemList[i].cargoOwnerId,
              formLocationId: data.chMoveLocationItemList[i].locationId,
              productId: data.chMoveLocationItemList[i].productId,
              toLocationId: data.chMoveLocationItemList[i].toLocationId,
              locationPackageId: data.chMoveLocationItemList[i].locationPackageId,
              locationMoveNum: data.chMoveLocationItemList[i].locationMoveNum
            })
          }
        }
        data.chMoveLocationItemList = tempArr
        data.memo = '移库单生成'
        let url = '/ms-warehouse-order/moveLocation/saveMoveInfo'
        this.$confirm('<p>确认移库？</p><p>系统将按照移库包件生成移库单</p>', '提示', {
          type: 'warning',
          center: true,
          dangerouslyUseHTMLString: true,
          confirmButtonText: '提交',
          cancelButtonText: '取消',
          beforeClose: (action, instance, done) => {
            instance.confirmButtonLoading = false
            if (action === 'confirm') {
              instance.confirmButtonLoading = true
              instance.confrimButtonText = '保存中...'
              this.$ajax.post(url, data).then(response => {
                const success = dotData(response, 'success')
                if (success) {
                  done()
                  instance.confirmButtonLoading = false
                  setTimeout(() => {
                    this.$confirm('保存成功', '提示', {
                      type: 'success',
                      center: true,
                      confirmButtonText: '确定',
                      showCancelButton: false,
                      closeOnClickModal: false
                    }).then(_ => {
                      this.$router.push({path: '/ss-oms/warehouse/transfer/index'})
                    })
                  }, 1000)
                } else {
                  done()
                  instance.confirmButtonLoading = false
                  setTimeout(() => {
                    this.$message({
                      type: 'error',
                      message: `提交失败`
                    })
                  }, 500)
                }
              })
            } else { done() }
          }
        })
      })
    }
  }
}
</script>
